package cn.rongdao.jrkabao.ui.remind;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.mifengkong.frwidget.switchbutton.CustomSwitch;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.remind.RemindBean;
import cn.rongdao.jrkabao.model.creditcard.AddCreditCardRemindModel;
import cn.rongdao.jrkabao.model.remind.DeleteRemindModel;
import cn.rongdao.jrkabao.model.remind.EditCreditCardModel;
import cn.rongdao.jrkabao.model.remind.RemindSwitchModel;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.SelectBankCardActivity;
import cn.rongdao.jrkabao.ui.remind.event.DeleteCardEvent;
import cn.rongdao.jrkabao.ui.remind.event.SaveCardEvent;
import cn.rongdao.jrkabao.ui.remind.uicomponent.EditCreditCardUIComponent;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.GetDefaultDataUtil;
import cn.rongdao.jrkabao.util.NumberUtil;
import cn.rongdao.jrkabao.widget.SelectDateFromBottom;

/**
 * Created by jack on 2017/9/11
 */

public class AddCreditCardRemindActivity extends BaseAutoFinishActivity {

    public static final String REMIND_ID = "remind_id";

    public static void start(Context context, String remindId) {
        Bundle bundle = new Bundle();
        bundle.putString(REMIND_ID, remindId);
        FRStartActivity.start(context, AddCreditCardRemindActivity.class, bundle);
    }

    @BindView(R.id.aaccr_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.aaccr_tv_save)
    TextView tvSave;
    @BindView(R.id.aaccr_layout_bankname)
    EditCreditCardUIComponent editCardBankName;
    @BindView(R.id.aaccr_layout_repaymentdate)
    EditCreditCardUIComponent editCardRepaymentDate;
    @BindView(R.id.aaccr_layout_card_holder)
    EditCreditCardUIComponent editCardHolder;
    @BindView(R.id.aaccr_layout_lastnumber)
    EditCreditCardUIComponent editCardLastNumber;
    @BindView(R.id.aaccr_layout_statementdate)
    EditCreditCardUIComponent editCardStatementDate;
    @BindView(R.id.aaccr_layout_quota)
    EditCreditCardUIComponent editCardQuota;
    @BindView(R.id.aaccr_layout_remind)
    EditCreditCardUIComponent editCardRemind;
    @BindView(R.id.aaccr_ll_main)
    LinearLayout llMain;


    private String bankName;
    private String bankCode;
    private String repaymentDate;
    private String name;
    private String lastNumber;
    private String billDate;
    private String quota;
    private String remindId;
    private boolean amountStatus = true;
    private boolean bankNameStatus = true;
    private boolean bankcardNoStatus = true;
    private boolean userNameStatus = true;
    private boolean billDayStatus = true;
    private boolean repayDayStatus = true;

    private boolean isAddCredit;
    private boolean isExample;
    private SelectDateFromBottom selectDateFromBottom;

    @Override
    protected int layoutRes() {
        return R.layout.activity_add_credit_card_remind;
    }

    @Override
    protected void initView() {
        super.initView();
        remindId = getIntent().getStringExtra(REMIND_ID);
        isAddCredit = FRString.isEmpty(remindId);
        if (!isAddCredit && remindId.equals("-1")) {
            isExample = true;
        }
        initTitleBar();
        initEditCard();
        selectDateFromBottom = new SelectDateFromBottom(thisActivity());
        selectDateFromBottom.setDataList(null);
        initListener();
    }

    private void initEditCard() {
        editCardBankName.setName("银行");
        editCardRepaymentDate.setName("还款");
        editCardHolder.setName("持卡人");
        editCardLastNumber.setName("尾号");
        editCardStatementDate.setName("账单日");
        editCardQuota.setName("信用额度");
        editCardRemind.setName("还款提醒");
        editCardQuota.setInputMoneyStyle();
        editCardLastNumber.setNumberStyle();
        editCardLastNumber.setNumberInputMaxLength(4);
        editCardHolder.setNumberInputMaxLength(4);

        if (isAddCredit) {
            setSaveText("确认添加");
            editCardRemind.setVisibility(View.GONE);
            setCreditCardInfo();
        } else {
            editCardRemind.setVisibility(View.VISIBLE);
            editCardRemind.setSwitchVisible();
            if (!isExample) {
                getBankCardInfo();
            } else {
                setExampleData();
            }
        }
    }

    private void setExampleData() {
        RemindBean.RemindBankList data = GetDefaultDataUtil.getExampleBean();
        bankName = data.getBank_name();
        repaymentDate = data.getRepay_day();
        name = data.getUser_name();
        lastNumber = data.getBankcard_no();
        billDate = data.getBill_day();
        quota = data.getAmount();
        setSaveText("保存");
        setCreditCardInfo();
    }

    private void setSaveText(String save) {
        llMain.setVisibility(View.VISIBLE);
        tvSave.setVisibility(View.VISIBLE);
        tvSave.setText(FRString.valueOf(save));
    }

    private void getBankCardInfo() {
        EditCreditCardModel.getInstance().execute(remindId, new FRBaseObserver<RemindBean.RemindBankList>(this, "加载中，请稍候...") {
            @Override
            protected void onBaseNext(RemindBean.RemindBankList data) {
                bankName = data.getBank_name();
                repaymentDate = data.getRepay_day();
                name = data.getUser_name();
                lastNumber = data.getBankcard_no();
                billDate = data.getBill_day();
                quota = data.getAmount();
                bankCode = data.getBank_code();
                editCardRemind.setCustomSwitchState(CommonUtil.isStatusSuccess(data.getIs_remind()));
                amountStatus = CommonUtil.isStatusSuccess(data.getAmount_status());
                bankNameStatus = CommonUtil.isStatusSuccess(data.getBank_name_status());
                bankcardNoStatus = CommonUtil.isStatusSuccess(data.getBankcard_no_status());
                userNameStatus = CommonUtil.isStatusSuccess(data.getUser_name_status());
                billDayStatus = CommonUtil.isStatusSuccess(data.getBill_day_status());
                repayDayStatus = CommonUtil.isStatusSuccess(data.getRepay_day_status());
                setCreditCardInfo();
                setSaveText("保存");
            }
        });
    }

    private void setCreditCardInfo() {
        editCardRepaymentDate.setViewLineGone();
        if (isAddCredit) {
            editCardQuota.setViewLineGone();
        }
        if (FRString.isEmpty(bankName)) {
            editCardBankName.setGrayContentText("选择银行");
        } else {
            editCardBankName.setBlackContent(bankName);
        }
        if (FRString.isEmpty(repaymentDate)) {
            editCardRepaymentDate.setGrayContentText("选择还款日");
        } else {
            editCardRepaymentDate.setBlackContent(FRCollection.appendAsString(repaymentDate, "日", ""));
        }
        if (FRString.isEmpty(name)) {
            editCardHolder.setInputHint("输入姓名");
        } else {
            if (!userNameStatus) {
                editCardHolder.setInputDisable();
            }
            editCardHolder.setInputContent(name);
        }
        if (FRString.isEmpty(lastNumber)) {
            editCardLastNumber.setInputHint("输入尾号");
        } else {
            if (!bankcardNoStatus) {
                editCardLastNumber.setInputDisable();
            }
            editCardLastNumber.setInputContent(lastNumber);
        }
        if (FRString.isEmpty(billDate)) {
            editCardStatementDate.setGrayContentText("选择账单日");
        } else {
            editCardStatementDate.setBlackContent(FRCollection.appendAsString(billDate, "日", ""));
        }
        if (FRString.isEmpty(quota)) {
            editCardQuota.setInputHint("0.00");
        } else {
            if (!amountStatus) {
                editCardQuota.setInputDisable();
            }
            editCardQuota.setInputContent(quota);
        }
    }

    private void initListener() {
        selectDateFromBottom.setOnSelectDateListener(new SelectDateFromBottom.OnSelectDateListener() {
            @Override
            public void getSelectDate(boolean isRepayment, final String number) {
                if (isRepayment) {
                    repaymentDate = NumberUtil.getNumberFromString(number);
                    editCardRepaymentDate.setBlackContent(number);
                } else {
                    billDate = NumberUtil.getNumberFromString(number);
                    editCardStatementDate.setBlackContent(number);
                }
                selectDateFromBottom.dismiss();
            }
        });
        editCardRemind.setCustomSwitchListener(new CustomSwitch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CustomSwitch customeSwitch, boolean checked) {
                if (isExample) {
                    editCardRemind.setCustomSwitchState(checked);
                    return;
                }
                if (!FRString.isEmpty(remindId)) {
                    remindSwitch(checked);
                }
            }
        });
    }

    private void remindSwitch(final boolean isChecked) {
        RemindSwitchModel.getInstance().execute(isChecked, remindId, new FRBaseObserver<String>(this) {
            @Override
            protected void onBaseNext(String data) {
                editCardRemind.setCustomSwitchState(isChecked);
            }
        });
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitle(isAddCredit ? "添加信用卡" : "编辑信用卡");
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary));
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (!isAddCredit) {
            titleBarUIComponent.setRightTextColor(R.color.white);
            titleBarUIComponent.initRight("删除", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDeleteCardDialog();
                }
            });
        }
    }

    private void showDeleteCardDialog() {
        new FRDialog.MDBuilder(this)
                .setMessage("删除后，你将无法收到信用卡还款提醒，确认删除吗？")
                .setNegativeContentAndListener("取消", null)
                .setNegativeTextColor(ContextCompat.getColor(thisActivity(), R.color.c333333))
                .setPositiveTextColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary))
                .setPositiveContentAndListener("确认",new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        deleteCard();
                        return true;
                    }
                })
                .show();
    }

    private void deleteCard() {
        if (isExample) {
            FRToast.showToastSafe("示例卡暂不能删除");
        } else {
            DeleteRemindModel.getInstance().execute(remindId, new FRBaseObserver<String>(this, "正在删除，请稍后...") {
                @Override
                protected void onBaseNext(String data) {
                    FRToast.showToastSafe("删除成功");
                    EventBus.getDefault().post(new DeleteCardEvent());
                    finish();
                }
            });
        }
    }

    @OnClick({R.id.aaccr_layout_bankname, R.id.aaccr_layout_repaymentdate, R.id.aaccr_layout_statementdate, R.id.aaccr_tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.aaccr_layout_bankname:
                if (bankNameStatus) {
                    SelectBankCardActivity.start(thisActivity(), true, SelectBankCardActivity.SELECT_BANK_CODE_RESULT_CODE);
                }
                break;
            case R.id.aaccr_layout_repaymentdate:
                if (repayDayStatus) {
                    selectDateFromBottom.setRepayment(true);
                    selectDateFromBottom.show();
                }
                break;
            case R.id.aaccr_layout_statementdate:
                if (billDayStatus) {
                    selectDateFromBottom.setRepayment(false);
                    selectDateFromBottom.show();
                }
                break;
            case R.id.aaccr_tv_save:
                if (isExample) {
                    return;
                }
                if (FRString.isEmpty(bankName)) {
                    FRToast.showToastSafe("请选择银行");
                    return;
                }
                if (FRString.isEmpty(repaymentDate)) {
                    FRToast.showToastSafe("请选择还款日");
                    return;
                }
                lastNumber = editCardLastNumber.getInputContent();
                if (!FRString.isEmpty(lastNumber) && lastNumber.length() < 4 && lastNumber.length() > 0) {
                    FRToast.showToastSafe("请填写信用卡尾号后四位");
                    return;
                }
                save();
                break;
        }
    }

    private void save() {
        AddCreditCardRemindModel.getInstance().execute(editCardQuota.getInputContent(), bankName, lastNumber, billDate
                , FRString.valueOf(remindId), repaymentDate, editCardHolder.getInputContent(), bankCode, new FRBaseObserver<String>(this, "保存中，请稍候...") {
                    @Override
                    protected void onBaseNext(String data) {
                        EventBus.getDefault().post(new SaveCardEvent());
                        FRToast.showToastSafe("保存成功");
                        finish();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SelectBankCardActivity.SELECT_BANK_CODE_RESULT_CODE
                && requestCode == SelectBankCardActivity.SELECT_BANK_CODE_RESULT_CODE) {
            bankName = FRString.valueOf(data.getStringExtra(SelectBankCardActivity.BANK_NAME));
            bankCode = FRString.valueOf(data.getStringExtra(SelectBankCardActivity.BANK_CODE));
            editCardBankName.setBlackContent(bankName);
        }
    }
}